package logs

import (
	"sync"
	"os"
	"strconv"
	"time"
	"fmt"
)


type fileLogWriter struct{
	sync.RWMutex

	FileName 	string		`json:"filename"`

	fileWriter 	*os.File

	Perm 		string		`json:"perm"`
}

func (w *fileLogWriter) Init(file string) error {
	perm, err := strconv.ParseInt(w.Perm, 8 ,64)
	if err != nil {
		return err
	}

	fd, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(perm))
	if err == nil {
		os.Chmod(w.FileName, os.FileMode(perm))
	}

	if w.fileWriter != nil {
		w.fileWriter.Close()
	}

	w.fileWriter = fd
	return nil
}

func (w *fileLogWriter) WriteMsg(when time.Time, msg string) error {
	t := fmt.Sprintf("%-22s", when.Format("2006-01-02 15:04:05.99"))
	msg = t + " " + msg + "\n"

	w.Lock()
	_, err := w.fileWriter.Write([]byte(msg))
	fmt.Print(msg)
	w.Unlock()
	return err
}

func (w *fileLogWriter) Destroy() {
	w.fileWriter.Close()
}

func (w *fileLogWriter) Flush() {
	w.fileWriter.Sync()
}


func newFileLogger(file string) LoggerInterface {
	l := &fileLogWriter{
		Perm: "0660",
	}

	err := l.Init(file)
	if err != nil {
		return nil
	}

	return l
}


